<template>
    <a-menu v-bind="$attrs" @menuItemClick="onMenuItemClick" :selected-keys="selectedKeys" :open-keys="openKeys"
        @sub-menu-click="onSubMenuClick">
        <menu-item v-for="item in data" :key="item.key" :item="item" />
    </a-menu>
</template>
<script setup>
import MenuItem from './MenuItem.vue';
import { useRoutesStore } from '@/stores/router';
import { watch } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
const { asyncRoute } = useRoutesStore()
const router = useRouter()
const route = useRoute()
const selectedKeys = ref([])
const openKeys = ref([])

defineProps({
    data: {
        type: Array,
        required: true
    }
})
watch(route, (newValue) => {
    loadSelectKeys(newValue.meta.key)
})

const onSubMenuClick = (key, newOpenKeys) => {
    openKeys.value = newOpenKeys
}

const changeSelectKeys = (key, menus, selectedKeysTemp) => {
    let result = false
    menus.forEach(item => {
        if (item.key === key) {
            selectedKeysTemp.push(item.activeMenu || item.key)
            result = true
        } else if (item.children && item.children.length > 0 && changeSelectKeys(key, item.children, selectedKeysTemp)) {
            selectedKeysTemp.push(item.key)
            result = true
        }
    })
    return result
}

const loadSelectKeys = (key) => {
    let selectedKeysTemp = []
    changeSelectKeys(key, asyncRoute.menus, selectedKeysTemp)
    selectedKeys.value = selectedKeysTemp;

}


const onMenuItemClick = (key) => {
    loadSelectKeys(key)

    let menu = menuMap.value.get(key)
    let path = menu.redirectUrl || menu.path
    if (!path) {
        return
    }

    if (path.startsWith("https://") || path.startsWith("http://")) {
        window.open(path, '_blank')
        return
    }

    router.push(path)

}

const menuMap = computed(() => {
    let map = new Map()
    loadMenu(asyncRoute.menus, map)
    return map
})

const loadMenu = (menus, map) => {
    menus.forEach(item => {
        map.set(item.key, item)
        if (item.children && item.children.length > 0) {
            loadMenu(item.children, map)
        }
    })
}

onMounted(() => {
    loadSelectKeys(route.meta.key)
    openKeys.value = selectedKeys.value
})
</script>
<style lang="less" scoped>
.arco-menu,
.arco-menu-dark .arco-menu-inline-header,
.arco-menu-inline,
.sarco-menu-inner,
.arco-menu-item,
.arco-menu-light .arco-menu-inline-header,
.arco-menu-selected {
    background-color: transparent;
}

.arco-menu-title {
    color: #ffffff;
}
</style>